//
//  BASearchViewController.swift
//  BadAir
//
//  Created by D on 2018/4/9.
//  Copyright © 2018年 D. All rights reserved.
//

import UIKit
import ObjectMapper

class BASearchViewController: UIViewController , UITableViewDelegate , UITableViewDataSource  {
    
    var searchBack :((_ city: String)->())?
    private var listArray: [BAAQICityModel] = []
    private var containsArray: [BAAQICityModel] = []
    private var tableView = UITableView()
    private let reuseIdentifier = "Cell"
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        setupUI()
        loadListData()
        
        
    }
    
    private func loadListData() {
        TNetworkingManager.shared.requestData(api: .APIChinaAirList) { (JSON) in
            let showapi_res_body = JSON["showapi_res_body"]
            let ret_code = showapi_res_body["ret_code"].int
            guard ret_code == 0 else {
                return
            }
            
            let listJSON = showapi_res_body["list"].arrayObject
            self.listArray = Mapper<BAAQICityModel>().mapArray(JSONArray: listJSON as! [[String : Any]])
            
        }
    }
    
    
    private func setupUI() {
        tableView.backgroundColor = UIColor("#E9ECF2")
        tableView.separatorStyle = .none
        tableView.delegate = self
        tableView.dataSource = self
        tableView.rowHeight = UITableViewAutomaticDimension
        tableView.contentInset = UIEdgeInsets(top: 20, left: 0, bottom: 0, right: 0)
        tableView.estimatedRowHeight = 115
        tableView.register(BASiteListCell.self, forCellReuseIdentifier: reuseIdentifier)
        view.addSubview(tableView)
        
        
        let naviView = UIView()
        view.addSubview(naviView)
        
        let shadowImg = #imageLiteral(resourceName: "img_shadow").resizableImage(withCapInsets: UIEdgeInsets(top: 50,left: 50,bottom: 50,right: 50), resizingMode: UIImageResizingMode.stretch)
        let shadowView = UIImageView(image: shadowImg)
        naviView.addSubview(shadowView)
        
        let backView = UIView()
        backView.backgroundColor = colorWhite
        backView.layer.cornerRadius = 15
        backView.layer.masksToBounds = true
        naviView.addSubview(backView)
        
        let searchBack = UIView()
        searchBack.backgroundColor = UIColor("#E9ECF2")
        searchBack.layer.cornerRadius = 23
        searchBack.layer.masksToBounds = true
        naviView.addSubview(searchBack)
        
        let closeButton = UIButton()
        closeButton.setImage(#imageLiteral(resourceName: "button_close_normal"), for: .normal)
        closeButton.setImage(#imageLiteral(resourceName: "button_close_selected"), for: .selected)
        closeButton.addTarget(self, action: #selector(closeView), for: .touchUpInside)
        naviView.addSubview(closeButton)
        let searchButton = UIButton()
        searchButton.setImage(#imageLiteral(resourceName: "button_search_normal"), for: .normal)
        searchButton.setImage(#imageLiteral(resourceName: "button_search_normal"), for: .selected)
        searchButton.addTarget(self, action: #selector(searchCity), for: .touchUpInside)
        naviView.addSubview(searchButton)
        
        let textFeild = UITextField()
        textFeild.borderStyle = .none
        textFeild.placeholder = "搜索城市"
        textFeild.becomeFirstResponder()
        textFeild.returnKeyType = .search
        textFeild.textColor = UIColor("#12213D")
        textFeild.font = UIFont.systemFont(ofSize: 15, weight: .regular)
        textFeild.addTarget(self, action: #selector(textChange(_:)), for: .allEditingEvents)
        naviView.addSubview(textFeild)
        
        
        
        
        naviView.snp.makeConstraints { (make) in
            make.top.left.right.equalToSuperview()
            make.height.equalTo(66)
        }
        backView.snp.makeConstraints { (make) in
            make.left.bottom.right.equalToSuperview()
            make.height.equalToSuperview().offset(20)
        }
        shadowView.snp.makeConstraints { (make) in
            make.left.right.equalToSuperview()
            make.bottom.equalTo(15)
            make.height.equalTo(100)
        }
        closeButton.snp.makeConstraints { (make) in
            make.left.equalTo(15)
            make.height.width.equalTo(20)
            make.centerY.equalToSuperview()
        }
        searchBack.snp.makeConstraints { (make) in
            make.top.equalTo(10)
            make.bottom.equalTo(-10)
            make.right.equalTo(-15)
            make.left.equalTo(closeButton.snp.right).offset(18)
        }
        searchButton.snp.makeConstraints { (make) in
            make.height.width.equalTo(20)
            make.centerY.equalToSuperview()
            make.right.equalTo(searchBack).offset(-18)
        }
        textFeild.snp.makeConstraints { (make) in
            make.left.equalTo(searchBack).offset(20)
            make.right.equalTo(searchButton.snp.left).offset(-20)
            make.centerY.equalTo(searchBack)
        }
        
        tableView.snp.makeConstraints { (make) in
            make.top.equalTo(naviView.snp.bottom)
            make.left.right.equalToSuperview()
            make.bottom.equalToSuperview()
        }
    }
    
    @objc private func closeView() {
        dismiss(animated: true, completion: nil)
        
    }
    @objc private func searchCity() {
        
    }
    
    
    
    // 输入内容变更时
    @objc private func textChange(_ textField: UITextField) {
        guard let text = textField.text else {
            return
        }
        
        
        containsArray.removeAll()
        for model in listArray {
            
            if model.area.contains(text) {
                containsArray.append(model)
            }
        }
        tableView.reloadData()
        print("containsArray: " , containsArray)
    }
//    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
//
//        guard let text = textField.text else {
//            return true
//        }
//
//
//        containsArray.removeAll()
//        for model in listArray {
//
//            if model.area.contains(text + string) {
//                containsArray.append(model)
//            }
//        }
//        print("containsArray: " , containsArray)
//
//        return true
//    }
    
    func textFieldDidEndEditing(_ textField: UITextField) {
        print("我已经结束编辑状态...")
    }
    func textFieldDidBeginEditing(_ textField: UITextField) {
        print("我正在编辑状态中...")
    }
    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        textField.resignFirstResponder()
        printDebug("text: " , textField.text ?? "")
        return true
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return containsArray.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = BASiteListCell(style: .subtitle, reuseIdentifier: reuseIdentifier)
        cell.model = containsArray[indexPath.row]
        return cell
    }
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 115
    }
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let cityName = containsArray[indexPath.row]
        searchBack?(cityName.area)
        dismiss(animated: true, completion: nil)
    }

}
